package cn.wolfcode.mq.listener;


import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mq.DefaultSendCallback;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: Ruomeng
 * @Date: 2025/1/29
 * @Description : shopseckill
 * @Version: 1.0
 */
@RocketMQMessageListener(
        consumerGroup = MQConstant.ORDER_PENDING_CONSUMER_GROUP,
        topic = MQConstant.ORDER_PENDING_TOPIC
)
@Component
@Slf4j
public class OrderPendingMessageListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage message) {
        log.info("[创建订单] 收到创建订单消息，准备开始创建订单：{}", JSON.toJSONString(message));
        OrderMQResult result = new OrderMQResult();
        result.setToken(message.getToken());
        try {
            // 调用秒杀接口进行秒杀
            OrderInfo orderInfo = orderInfoService.doSeckill(message.getUserPhone(), message.getSeckillId(), message.getTime());
            String orderNo = orderInfo.getOrderNo();
            // 订单创建成功
            result.setOrderNo(orderNo);
            result.setCode(Result.SUCCESS_CODE);
            result.setMsg("订单创建成功");

            // 当订单下单成功后, 发送延时消息, 检查订单支付状态, 超过时间未支付直接取消订单
            message.setOrderNo(orderNo);
            Message<OrderMessage> orderMessage = MessageBuilder.withPayload(message).build();
            // 延迟等级：1s、5s、10s、30s、1m、2m、3m、4m、5m、6m、7m、8m、9m、10m、20m、30m、1h、2h
            rocketMQTemplate.asyncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, orderMessage,
                    new DefaultSendCallback("订单超时未支付"), 2000, 3);
        } catch (Exception e) {
            // 订单创建失败
            result.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            result.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            // 回补Redis数量控制 & 删除用户下单标识 & 删除本地下单标识
            orderInfoService.failedRollback(message);
        }
        // 发送订单创建结果消息
        rocketMQTemplate.asyncSend(MQConstant.ORDER_RESULT_TOPIC, result, new DefaultSendCallback("订单结果"));
    }

}
